<template>
    <div class="home">
        <!-- 搜索框 -->
        <van-search shape="round" background="#8EC5FC" placeholder="请输入搜索关键词" show-action action-text="登录"
            @cancel="handleLogin" readonly @click-input="handleSearch">

            <!-- 自定义左侧图标 -->
            <template #left>
                <van-icon name="location-o" size="32px" color="#F00" style="margin-right: 8px;" />
            </template>
        </van-search>

        <!-- 轮播图 -->
        <van-swipe class="home-swipe" height="150" vertical :autoplay="3000">
            <van-swipe-item v-for="img in bannerses" :key="img.id">
                <img :src="img.image" style="width: 100%; height: 100%;" />
            </van-swipe-item>
        </van-swipe>
        <!-- 原生 seiper -->
        <!-- <div class="swiper-container">
            <div class="swiper-wrapper">
                <div class="swiper-slide" v-for="img in banners" :key="img.id">
                    <img :src="img.image" style="width: 100%; height: 100%;" />
                </div>
            </div>
            
            <div class="swiper-pagination"></div>
        </div> -->

        <!-- 宫格-专题 -->
        <van-grid :column-num="5" :border="false">
            <van-grid-item v-for="value in gridData" :key="value.text" :icon="value.icon" :text="value.text" />
        </van-grid>

        <!-- 秒杀专题 -->
        <div class="sec-kill">
            <div class="sec-kill-title">
                <span style="margin-right: 6px">秒杀</span>
                <span class="period">{{ currentPeriod }}</span>
                <van-count-down :time="seckillTime">
                    <template #default="timeData">
                        <span class="block">{{ pad(timeData.hours) }}</span>
                        <span class="colon">:</span>
                        <span class="block">{{ pad(timeData.minutes) }}</span>
                        <span class="colon">:</span>
                        <span class="block">{{ pad(timeData.seconds) }}</span>
                    </template>
                </van-count-down>
            </div>
            <div class="sec-kill-body">
                <div class="sec-kill-item" v-for="prod in seckilllist" :key="prod.id">
                    <img :src="prod.image" alt="">
                    <span class="price">￥{{ money(prod.price) }}</span>
                </div>
            </div>
        </div>

        <!-- 推荐商品列表 -->
        <!-- 分割线 -->
        <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
            大众好评
        </van-divider>

        <!-- 将请求接口数据的方法传给子组件 -->
        <!-- 这里的<list-product>标签 要和接收引入子组件的变量一致！！-->
        <list-product :requestApi="getRecommendList" @click-item="handleJumpToDetail">
            <!-- <template #originprice>
                <van-button type="danger" size="mini">加入购物车</van-button>
            </template> -->
        </list-product>


    </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
// @ts-ignore
import Swiper from 'swiper/swiper-bundle.min'
import 'swiper/swiper-bundle.min.css'
import { ref, /* onMounted, onUpdated, */ /* nextTick  */ } from 'vue'
import { getBanners, getSeckilllist, getRecommendList } from '@/api/home'
import ListProduct from '@/components/list-product/index.vue'

// 获取路由对象的引用
const router = useRouter()

// 轮播图数组
const bannerses = ref<Banner[]>([])

/**
  * 根据图像名称，获取图像 URL 资源
  */
function getImageUrl(name: number) {
    return new URL(`../../assets/${name}.png`, import.meta.url).href
}

// 宫格导航数据
const gridData = [
    {
        text: '新之助',
        icon: getImageUrl(1),
    },
    {
        text: '皮卡丘',
        icon: getImageUrl(2),
    },
    {
        text: '新之助',
        icon: getImageUrl(1),
    },
    {
        text: '皮卡丘',
        icon: getImageUrl(2),
    },
    {
        text: '新之助',
        icon: getImageUrl(1),
    },
    {
        text: '皮卡丘',
        icon: getImageUrl(2),
    },
    {
        text: '新之助',
        icon: getImageUrl(1),
    },
    {
        text: '皮卡丘',
        icon: getImageUrl(2),
    },
    {
        text: '新之助',
        icon: getImageUrl(1),
    },
    {
        text: '皮卡丘',
        icon: getImageUrl(2),
    },
]

// ________________________________________
// 秒杀商品数据
const seckilllist = ref<Product[]>([])

// 秒杀时间段
const periods = [0, 8, 12, 14, 18, 24]
// 当前场次
const currentPeriod = ref<string>('0点场')

// 秒杀商品的时间
const seckillTime = ref<number>(24 * 60 * 60 * 1000)



// 计算秒杀倒计时时间
const calcSeckillTime = () => {
    // 获取当前时间
    const datetime = new Date()
    // 计算当前场次
    const currHours = datetime.getHours()
    let i = 0
    for (let len = periods.length; i < len; i++) {
        if (currHours < periods[i]) {
            break
        }
    }
    currentPeriod.value = `${periods[i - 1]}点场`
    // 计算距离下一场倒计时时间
    const nextDatetime = new Date(datetime.getFullYear(), datetime.getMonth(), datetime.getDate(), periods[i], 0, 0)
    seckillTime.value = nextDatetime.getTime() - Date.now()
}

calcSeckillTime()

// pad()
const pad = (val: string | number, len = 2) => {
    return String(val).padStart(len, '0')
}

// 格式化金额数字，小数点后显示两位小数
const money = (val: string | number) => {
    return Number(val).toFixed(2)
}

// ________________________________________
// 登录处理
const handleLogin = () => {
    return router.push('/login')
}

//搜索处理
const handleSearch = () => {
    return router.push('/search')
}

// 查询首页数据图数据
const fetchHomeData = async () => {

    // Promise.all([])
    const [result, res,/* recommend */]: any = await Promise.all([
        getBanners(), // 轮播图
        getSeckilllist(), // 秒杀商品
        // getRecommendList(), // 推荐商品列表
    ])
    console.log('result:', result.banners)
    console.log('res:', res.list)

    // 轮播数据
    bannerses.value = result.banners
    // 秒杀数据
    seckilllist.value = res.list

    // 创建 swiper 对象实例，
    // 虽然响应式数据改变了，但
    // 实际页面还没有实现 DOM 更新
    // 要获得到数据更新后重新渲染的 DOM
    // 进行处理，则需要调用 nextTick() 方法
    // nextTick(callback) 会将 callback
    // 回调函数的执行延迟到下一次 DOM 更新后执行

    /* 原生的话就添加 */
    /* nextTick(() => {
        new Swiper('.swiper-container', {
            loop: true, // 循环模式选项
            autoplay: true,
            effect: 'cube',

            // 如果需要分页器
            pagination: {
                el: '.swiper-pagination',
            },
        })
    }) */
}

fetchHomeData()

// 跳转到详情页面处理
const handleJumpToDetail = (prod: Product) => {
    console.log('---->', prod);

    router.push({
        name: 'detail',
        params: {
            id: prod.id
        }
    })
}
</script>


<style lang="less" scoped>



.home {
    background-color: rgb(142, 197, 252);
}

:deep(.recommend-list-item) {
    border: 1px solid red;
    margin-bottom: 20px;
    font-size: 12px;
}

:deep(.recommend-list-item):hover {
    box-shadow: 0 0 14px red;
}

.van-button--plain {
    background: transparent;
}

.van-button--plain.van-button--danger {
    color: #fff;
}

// 样式穿透(面试): 利用深度选择器实现
:deep(.van-search__action) {
    color: #fff;
}

.home-swipe {
    width: 375px;
    height: 150px;
}

.swiper-container {
    width: 375px;
    height: 150px;
}

/* 宫格  */
// .van-icon__image {
//     width: 34px;
//     height: 34px;
// }

.sec-kill {
    width: 375px;
    overflow: hidden;
    margin-top: 12px;

    &-title {
        display: flex;
        font-size: 16px;
        font-weight: 700;
        align-items: center;
        padding: 0 12px;

        .period {
            color: #f00;
            font-size: 14px;
            font-weight: 400;
            margin-right: 6px;
        }

        .colon {
            display: inline-block;
            margin: 0 4px;
            color: #F00;
        }

        .block {
            display: inline-block;
            width: 22px;
            color: #fff;
            font-size: 12px;
            text-align: center;
            background-color: #F00;
            border-radius: 4px;
        }
    }

    &-body {
        overflow: auto;
        display: flex;
    }

    &-item {
        width: 160px;
        height: 140px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-around;
        margin-right: 4px;

        img {
            width: 120px;
            height: 100px;
        }

        .price {
            color: #f00;
        }
    }
}



// // 推荐商品
// .recommend-list {
//   width: 375px;
//   display: flex;
//   flex-wrap: wrap;
//   justify-content: space-between;

//   // .recommend-list-item
//   &-item {
//     width: 180px;
//     height: 180px;
//     display: flex;
//     flex-direction: column;
//     justify-content: space-between;
//     align-items: center;

//     img {
//       width: 160px;
//       height: 120px;
//     }
//   }
// }
</style>
